package edu.scau.divineplace.config.global.data.convert;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * @Author: x1aolone
 * @Date: 2021/1/21 17:09
 * 需要序列化/反序列化 LocalDateTime的时候，会以 PATTERN 的格式进行转换
 * 缺点是全局只能使用这种方式对数据进行序列化和反序列化，不能根据不同的业务进行定制
 * 返回结果需要定制时可以在需要的地方自建Date工具转换为String
 * 入参尚未有解决方案
 */
@Configuration
public class LocalDateTimeConfig {


    private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);

    /**
     * 解决RequestParam接受时的反序列化
     * @return
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConvert() {
        // 不能用lambda, 会启动失败
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return LocalDateTime.parse(source, FORMATTER);
            }
        };
    }

    /**
     * 解决返回值的序列化和RequestBody接受时的反序列化
     * @return
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizeLocalDateTimeFormat() {
        return jacksonObjectMapperBuilder -> {
            LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(FORMATTER);
            LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(FORMATTER);
            jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, serializer);
            // 这种反序列化只能解决RequestBody传参，使用Swagger可以传的到，使用Postman form-data、x-www、raw都失败
            jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, deserializer);
        };
    }

}
